<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>代码分析 - AI Worker</title>
    <!-- Marked.js for Markdown rendering -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #0e7490 0%, #0891b2 50%, #06b6d4 100%);
            min-height: 100vh;
            padding: 30px 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }

        .header-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .page-title {
            font-size: 2em;
            color: #333;
            font-weight: 600;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-primary {
            background: linear-gradient(135deg, #0891b2 0%, #0e7490 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(8, 145, 178, 0.3);
        }

        .btn-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }

        .content {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }

        .section-title {
            font-size: 1.3em;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #0891b2;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group input[type="text"],
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-size: 1em;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #0891b2;
            box-shadow: 0 0 0 3px rgba(8, 145, 178, 0.1);
        }

        .required {
            color: #dc3545;
        }

        .help-text {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }

        /* 项目多选框 */
        .projects-selector {
            border: 2px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            max-height: 300px;
            overflow-y: auto;
        }

        .project-item {
            padding: 12px;
            margin-bottom: 10px;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            background: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .project-item:hover {
            background: #e9ecef;
            border-color: #0891b2;
        }

        .project-item.selected {
            background: #ecfeff;
            border-color: #0891b2;
            border-width: 2px;
        }

        .project-item input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .project-info {
            flex: 1;
        }

        .project-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }

        .project-detail {
            font-size: 0.9em;
            color: #666;
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #0891b2;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #dc3545;
        }

        .success-message {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #28a745;
        }

        .result-section {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #dee2e6;
        }

        .result-content {
            line-height: 1.8;
            color: #333;
        }

        /* Markdown样式 */
        .result-content h1 {
            font-size: 2em;
            margin: 20px 0 15px 0;
            padding-bottom: 10px;
            border-bottom: 2px solid #0891b2;
            color: #333;
        }

        .result-content h2 {
            font-size: 1.6em;
            margin: 18px 0 12px 0;
            color: #0891b2;
        }

        .result-content h3 {
            font-size: 1.3em;
            margin: 15px 0 10px 0;
            color: #555;
        }

        .result-content h4 {
            font-size: 1.1em;
            margin: 12px 0 8px 0;
            color: #666;
        }

        .result-content p {
            margin: 10px 0;
            line-height: 1.8;
        }

        .result-content ul, .result-content ol {
            margin: 10px 0;
            padding-left: 30px;
        }

        .result-content li {
            margin: 5px 0;
        }

        .result-content code {
            background: #f5f5f5;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 0.9em;
            color: #d63384;
        }

        .result-content pre {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #0891b2;
            overflow-x: auto;
            margin: 15px 0;
        }

        .result-content pre code {
            background: none;
            padding: 0;
            color: #333;
            font-size: 0.95em;
        }

        .result-content blockquote {
            border-left: 4px solid #0891b2;
            padding-left: 15px;
            margin: 15px 0;
            color: #666;
            font-style: italic;
        }

        .result-content table {
            border-collapse: collapse;
            width: 100%;
            margin: 15px 0;
        }

        .result-content table th,
        .result-content table td {
            border: 1px solid #dee2e6;
            padding: 10px;
            text-align: left;
        }

        .result-content table th {
            background: #f8f9fa;
            font-weight: 600;
        }

        .result-content a {
            color: #0891b2;
            text-decoration: none;
        }

        .result-content a:hover {
            text-decoration: underline;
        }

        .result-content strong {
            font-weight: 600;
            color: #333;
        }

        .result-content em {
            font-style: italic;
        }

        .result-content hr {
            border: none;
            border-top: 2px solid #e9ecef;
            margin: 20px 0;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-top">
                <h1 class="page-title">📊 代码分析</h1>
                <button class="btn btn-secondary" onclick="goBack()">← 返回项目</button>
            </div>
        </div>

        <div class="content">
            <div id="messageContainer"></div>

            <form id="analyzeForm" onsubmit="submitAnalysis(event)">
                <!-- 项目选择 -->
                <div class="form-section">
                    <div class="section-title">1️⃣ 选择要分析的项目</div>
                    <div class="help-text" style="margin-bottom: 15px;">
                        请选择本次需求涉及的代码项目（可多选）
                    </div>
                    <div id="projectsSelector" class="projects-selector">
                        <div class="loading">
                            <div class="spinner"></div>
                            <p>加载项目配置中...</p>
                        </div>
                    </div>
                </div>

                <!-- MR地址 -->
                <div class="form-section">
                    <div class="section-title">2️⃣ MR信息</div>
                    <div class="form-group">
                        <label for="mrUrl">
                            MR地址 <span class="required">*</span>
                        </label>
                        <input 
                            type="text" 
                            id="mrUrl" 
                            name="mrUrl"
                            placeholder="请先选择项目后再输入MR地址"
                            required
                            disabled
                        >
                        <div class="help-text" id="mrHelp">
                            请先选择至少一个项目，然后输入GitLab Merge Request 的完整URL
                        </div>
                    </div>
                </div>

                <!-- 提交按钮 -->
                <div class="action-buttons">
                    <button type="submit" class="btn btn-success" id="submitBtn">
                        🔍 开始分析
                    </button>
                    <button type="button" class="btn btn-secondary" onclick="resetForm()">
                        🔄 重置
                    </button>
                </div>
            </form>

            <!-- 分析结果 -->
            <div id="resultSection" style="display: none;">
                <div class="section-title">📋 分析结果</div>
                <div class="result-section">
                    <div id="resultContent" class="result-content"></div>
                </div>
                <div class="action-buttons">
                    <button class="btn btn-primary" onclick="downloadResult()">
                        💾 下载结果
                    </button>
                    <button class="btn btn-secondary" onclick="startNewAnalysis()">
                        🔄 新建分析
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const projectId = window.location.pathname.split('/')[2];
        let gitlabProjects = [];
        let analysisResult = null;

        // 页面加载
        window.onload = function() {
            loadGitlabProjects();
        };

        // 加载GitLab项目配置
        async function loadGitlabProjects() {
            try {
                const response = await fetch('/api/gitlab/projects');
                if (!response.ok) throw new Error('加载失败');
                
                const data = await response.json();
                gitlabProjects = data.projects || [];
                renderProjects();
            } catch (error) {
                showError('加载项目配置失败: ' + error.message);
                document.getElementById('projectsSelector').innerHTML = `
                    <div class="empty-state">
                        <p>❌ 加载项目配置失败</p>
                        <p style="margin-top: 10px; font-size: 0.9em;">请检查config.yaml中的gitlab.projects配置</p>
                    </div>
                `;
            }
        }

        // 渲染项目列表
        function renderProjects() {
            const container = document.getElementById('projectsSelector');
            
            if (!gitlabProjects || gitlabProjects.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <p>暂无项目配置</p>
                        <p style="margin-top: 10px; font-size: 0.9em;">请在config.yaml中配置gitlab.projects</p>
                    </div>
                `;
                return;
            }
            
            const html = gitlabProjects.map((project, index) => `
                <div class="project-item" onclick="toggleProject(${index})" id="project-${index}">
                    <input 
                        type="checkbox" 
                        id="checkbox-${index}"
                        value="${escapeHtml(project.name)}"
                        onclick="event.stopPropagation(); toggleProject(${index})"
                    >
                    <div class="project-info">
                        <div class="project-name">${escapeHtml(project.name)}</div>
                        <div class="project-detail">
                            📁 ${escapeHtml(project.repo_url)}<br>
                            🌿 默认分支: ${escapeHtml(project.default_branch)}
                        </div>
                    </div>
                </div>
            `).join('');
            
            container.innerHTML = html;
        }

        // 切换项目选择
        function toggleProject(index) {
            const item = document.getElementById(`project-${index}`);
            const checkbox = document.getElementById(`checkbox-${index}`);
            
            checkbox.checked = !checkbox.checked;
            
            if (checkbox.checked) {
                item.classList.add('selected');
            } else {
                item.classList.remove('selected');
            }
            
            // 更新MR输入框状态
            updateMRInputState();
        }

        // 更新MR输入框状态
        function updateMRInputState() {
            const mrUrlInput = document.getElementById('mrUrl');
            const mrHelp = document.getElementById('mrHelp');
            const submitBtn = document.getElementById('submitBtn');
            
            // 检查是否有选中的项目
            const hasSelected = gitlabProjects.some((project, index) => {
                const checkbox = document.getElementById(`checkbox-${index}`);
                return checkbox && checkbox.checked;
            });
            
            if (hasSelected) {
                // 启用MR输入框
                mrUrlInput.disabled = false;
                mrUrlInput.placeholder = 'https://gitlab.com/your-org/project/-/merge_requests/123';
                mrHelp.textContent = 'GitLab Merge Request 的完整URL，将重点分析此MR中的代码变更';
                mrHelp.style.color = '#666';
            } else {
                // 禁用MR输入框
                mrUrlInput.disabled = true;
                mrUrlInput.value = '';
                mrUrlInput.placeholder = '请先选择项目后再输入MR地址';
                mrHelp.textContent = '⚠️ 请先选择至少一个项目';
                mrHelp.style.color = '#dc3545';
            }
        }

        // 提交分析
        async function submitAnalysis(event) {
            event.preventDefault();
            
            // 获取选中的项目
            const selectedProjects = [];
            gitlabProjects.forEach((project, index) => {
                const checkbox = document.getElementById(`checkbox-${index}`);
                if (checkbox && checkbox.checked) {
                    selectedProjects.push({
                        name: project.name,
                        repo_url: project.repo_url,
                        branch: project.default_branch
                    });
                }
            });
            
            if (selectedProjects.length === 0) {
                showError('请至少选择一个项目');
                return;
            }
            
            const mrUrl = document.getElementById('mrUrl').value.trim();
            if (!mrUrl) {
                showError('请输入MR地址');
                return;
            }
            
            // 禁用提交按钮
            const submitBtn = document.getElementById('submitBtn');
            const originalText = submitBtn.textContent;
            submitBtn.disabled = true;
            submitBtn.textContent = '🔄 分析中...';
            
            try {
                const response = await fetch(`/api/project/${projectId}/analyze`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        projects: selectedProjects,
                        mr_url: mrUrl
                    })
                });
                
                const result = await response.json();
                
                if (!response.ok || !result.success) {
                    throw new Error(result.error || '分析失败');
                }
                
                // 显示结果
                analysisResult = result.analysis;
                displayResult(result.analysis);
                showSuccess('分析完成！');
                
            } catch (error) {
                showError('分析失败: ' + error.message);
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        }

        // 显示分析结果
        function displayResult(analysis) {
            document.getElementById('analyzeForm').style.display = 'none';
            document.getElementById('resultSection').style.display = 'block';
            
            const resultContent = document.getElementById('resultContent');
            const markdownText = analysis.result || analysis.analysis_result || '无分析结果';
            
            // 使用marked.js渲染markdown
            if (typeof marked !== 'undefined') {
                // 配置marked选项
                marked.setOptions({
                    breaks: true,
                    gfm: true
                });
                resultContent.innerHTML = marked.parse(markdownText);
            } else {
                // 如果marked.js未加载，显示纯文本
                resultContent.textContent = markdownText;
            }
        }

        // 下载结果
        function downloadResult() {
            if (!analysisResult) return;
            
            const content = analysisResult.result || analysisResult.analysis_result || '';
            const blob = new Blob([content], { type: 'text/markdown' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `code_analysis_${Date.now()}.md`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        // 开始新分析
        function startNewAnalysis() {
            document.getElementById('analyzeForm').style.display = 'block';
            document.getElementById('resultSection').style.display = 'none';
            resetForm();
        }

        // 重置表单
        function resetForm() {
            document.getElementById('analyzeForm').reset();
            
            // 取消所有选中
            gitlabProjects.forEach((project, index) => {
                const item = document.getElementById(`project-${index}`);
                const checkbox = document.getElementById(`checkbox-${index}`);
                if (item && checkbox) {
                    checkbox.checked = false;
                    item.classList.remove('selected');
                }
            });
            
            clearMessages();
        }

        // 返回
        function goBack() {
            window.location.href = `/project/${projectId}`;
        }

        // 显示错误
        function showError(message) {
            const container = document.getElementById('messageContainer');
            container.innerHTML = `<div class="error-message">${escapeHtml(message)}</div>`;
            container.scrollIntoView({ behavior: 'smooth' });
        }

        // 显示成功
        function showSuccess(message) {
            const container = document.getElementById('messageContainer');
            container.innerHTML = `<div class="success-message">${escapeHtml(message)}</div>`;
            setTimeout(() => container.innerHTML = '', 5000);
        }

        // 清除消息
        function clearMessages() {
            document.getElementById('messageContainer').innerHTML = '';
        }

        // 辅助函数
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>
